package sitemaps;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
import java.util.zip.GZIPOutputStream;

import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;

public class SitemapTransformer {
	private static final Logger LOG = Logger.getLogger(Sitemap.class.getName());
	private static final String GZ = ".gz";
	private final TransformerFactory factory;
	private DOMSource source;
	
	public SitemapTransformer() {
		//<expensive> 
		factory = TransformerFactory.newInstance();
		//</expensive>
	}
	
	public void setDocument(Document document) {
		source = new DOMSource(document);
	}

	private OutputStream createOutputStream(String outputFilename) throws IOException {
		final FileOutputStream fileOutputStream = new FileOutputStream(outputFilename);
		if(outputFilename.toLowerCase().endsWith(GZ))
			return new GZIPOutputStream(fileOutputStream);
		else 
			return fileOutputStream;
	}
	
	private InputStream openTemplateStream(String templateFilename) {
		return getClass().getResourceAsStream(templateFilename);
	}
	
	public void output(String templateFilename, String outputFilename) throws IOException, TransformerException {
		InputStream templateStream = null;
		OutputStream outputStream = null;
		try { 
			outputStream = createOutputStream(outputFilename);
			templateStream = openTemplateStream(templateFilename);
			final StreamResult result = new StreamResult(outputStream);
			final StreamSource templateSource = new StreamSource(templateStream);
			final Templates templates = factory.newTemplates(templateSource);
	        final Transformer transformer = templates.newTransformer();
	        transformer.transform(source, result);
			LOG.info("Sitemap: " + outputFilename);
		} finally { 
			try {
				if(outputStream != null) outputStream.close();
			} finally {
				if(templateStream != null) templateStream.close();
			}
		}
	}
	
	
}
